package com.tuyan.aixiang.util;

import android.app.Activity;
import android.content.Intent;

import com.tuyan.aixiang.activity.add.AddDeviceActivity;
import com.tuyan.aixiang.activity.config.SmartConfigActivity;
import com.tuyan.aixiang.activity.config.WifiConfigActivity;
import com.tuyan.aixiang.common.Constant;
import com.tuyan.aixiang.enums.YsDeviceType;
import com.tuyan.aixiang.model.YsDevice;
import com.videogo.openapi.EZOpenSDK;
import com.videogo.openapi.bean.EZProbeDeviceInfo;
import com.videogo.openapi.bean.EZProbeDeviceInfoResult;

public class YSUtil {

    private static final String TAG = "YSUtil";

    /**
     * 解析二维码
     * 获得萤石设备信息
     *
     * @param deviceInfo
     * @return
     */
    public static YsDevice getYsDevice(String deviceInfo) {
        if (null == deviceInfo) return null;
        try {
            deviceInfo = deviceInfo.replaceAll("\\r", "\n");
            String[] infos = deviceInfo.trim().split("\\n");

            if (infos.length < 3) return null;
            YsDevice device = new YsDevice();
            device.setTag(infos[0].trim());
            device.setDeviceSerial(infos[1].trim());
            device.setVerifyCode(infos[2].trim());
            device.setModelType(getModelType(infos[3].trim()));
            return device;
        } catch (Exception e) {
            return null;
        }
    }

    public static String getModelType(String type) {
        String[] arr = type.split(" ");
        return arr[0];
    }

    public static void gotoDeviceConfig(Activity activity, YsDevice device) {
        new Thread(() -> {
            final EZProbeDeviceInfoResult result = EZOpenSDK.probeDeviceInfo(device.getDeviceSerial(), device.getModelType());
            if (result.getBaseException() == null) {
                // TODO 直接添加设备
                activity.runOnUiThread(() -> {
//                    ToastUtil.makeShort("直接添加此设备");
                    EZProbeDeviceInfo probeDeviceInfo = result.getEZProbeDeviceInfo();
                    // 查询到设备信息，根据能力级选择配网方式
                    device.setDisplayName(probeDeviceInfo.getDisplayName());
                    device.setFullSerial(probeDeviceInfo.getFullSerial());
                    device.setDefaultPicPath(probeDeviceInfo.getDefaultPicPath());

                    Intent intent = new Intent(activity, AddDeviceActivity.class);
                    intent.putExtra("device", device);
                    activity.startActivity(intent);
                    activity.finish();
                });
                return;
            } else {
                switch (result.getBaseException().getErrorCode()) {
                    case 120023:
                        // TODO: 2018/6/25  设备不在线，未被用户添加 （这里需要网络配置）
                    case 120002:
                        // TODO: 2018/6/25  设备不存在，未被用户添加 （这里需要网络配置）
                    case 120029:
                        // TODO: 2018/6/25  设备不在线，已经被自己添加 (这里需要网络配置)
                        activity.runOnUiThread(() -> {
                            if (result.getEZProbeDeviceInfo() == null) {
                                // 未查询到设备信息，不确定设备支持的配网能力,需要用户根据指示灯判断
                                //若设备指示灯红蓝闪烁，请选择smartconfig配网
                                //若设备指示灯蓝色闪烁，请选择设备热点配网

                            } else {
                                EZProbeDeviceInfo probeDeviceInfo = result.getEZProbeDeviceInfo();
                                // 查询到设备信息，根据能力级选择配网方式
                                device.setDisplayName(probeDeviceInfo.getDisplayName());
                                device.setFullSerial(probeDeviceInfo.getFullSerial());
                                device.setDefaultPicPath(probeDeviceInfo.getDefaultPicPath());

                                if (probeDeviceInfo.getSupportAP() == 2) {
                                    //选择设备热点配网
                                    String model = device.getModel();
                                    device.setType(YsDeviceType.getValueByName(model));
                                    Intent intent = new Intent(activity, WifiConfigActivity.class);
                                    intent.putExtra("device", device);
                                    activity.startActivity(intent);
                                    activity.finish();
                                    return;
                                }
                                if (probeDeviceInfo.getSupportWifi() == 3) {
                                    //选择smartconfig配网
                                    String model = device.getModel();
                                    device.setType(YsDeviceType.getValueByName(model));
                                    Intent intent = new Intent(activity, SmartConfigActivity.class);
                                    intent.putExtra("device", device);
                                    activity.startActivity(intent);
                                    activity.finish();
                                    return;
                                }

                                ToastUtil.makeShort("不支持此设备配网");
                                activity.finish();
//                                if (probeDeviceInfo.getSupportSoundWave() == 1) {
//                                    //选择声波配网
//                                }
                            }
                        });
                        break;
                    case 120020:
                        // TODO: 2018/6/25 设备在线，已经被自己添加 (给出提示)
                    case 120022:
                        // TODO: 2018/6/25  设备在线，已经被别的用户添加 (给出提示)
                    case 120024:
                        // TODO: 2018/6/25  设备不在线，已经被别的用户添加 (给出提示)
                        activity.runOnUiThread(() -> {
                            ToastUtil.makeShort("此设备已经被添加");
                            activity.finish();
                        });
                        break;
                    default:
                        // TODO: 2018/6/25 请求异常
                        activity.runOnUiThread(() -> {
                            ToastUtil.makeShort("查询设备状态异常,请稍后重试");
                            Log.d(TAG, "Request failed = "
                                    + result.getBaseException().getErrorCode());
                            activity.finish();
                        });
                        break;
                }
            }
        }).start();
    }

    public static String getEzopenUrl(YsDevice device, boolean hd, boolean validate) {
        String protocal = "ezopen://";
        String validateCode = device.getValidateCode();
        String domain = "open.ys7.com";
        String deviceSerial = device.getDeviceSerial();
        String channelNum = device.getChannelNo() + "";
        String hdFlag = ".hd";
        String subfix = ".live";
        StringBuilder sb = new StringBuilder();
        sb.append(protocal);

        if (validate) {
            sb.append(validateCode);
            sb.append("@");
        }

        sb.append(domain);
        sb.append("/");
        sb.append(deviceSerial);
        sb.append("/");
        sb.append(channelNum);
        if (hd) {
            sb.append(hdFlag);
        }
        sb.append(subfix);
        Log.d(TAG, sb.toString());
        return sb.toString();
    }

    public static String getEzopenUrl(YsDevice device, boolean validate) {

        return getEzopenUrl(device, false, validate);
    }


    public static String[] cameraModel = {
            "CS-C6HC-3B1WFR",   // 摄像头
            "CS-DP1-4A1WPFBSR-B" // 猫眼
    };

    public static String[] socketModel = {
            "CS-T30-10A"    // 插座
    };

    public static String[] alarmModel = {
            "CS-A2-32W",
            "JY-BW01"
    };

    public static String getModelType(YsDevice device) {
        if (isInArray(device, cameraModel)) return Constant.MODEL_CAMERA;
        if (isInArray(device, alarmModel)) return Constant.MODEL_ALARM;
        if (isInArray(device, socketModel)) return Constant.MODEL_SOCKET;
        Log.d(TAG, "cannot get ModelType from list [" + device.getModelType());
        // 找不到已有型号
//        String deviceSerial = device.getDeviceSerial();
////        if (deviceSerial.startsWith("D") || deviceSerial.startsWith("C")) {
////            return Constant.MODEL_CAMERA;
////        }
////        if (deviceSerial.contains("Q")) {
////            return Constant.MODEL_ALARM;
////        }
        return Constant.MODEL_ALARM;
    }

    public static boolean isInArray(YsDevice device, String[] arr) {
        for (String s : arr) {
            String[] m1 = s.split("-");
            String[] m2 = device.getModelType().split("-");
            if(m2.length >= m1.length) {
                if(m2[0].equals(m1[0]) && m2[1].equals(m1[1])) {
                    return true;
                }
            }
        }
        return false;
    }

}


// 摄像头
//ys7
//        204019411
//        SZJQND
//        CS-C6HC-3B1WFR

// 丙烷
//  www.ys7.com
//  D82062349
//  CAFNDT
//  JY-BW01

// 网关
// ys7
//Q03055488 序列号
//DJZBRO    验证码
//CS-A2-32W  型号


// 烟感
//ys7
//        864697538
//        ABCDEF
//        CS-T4-B
//        T004

// 插座
//  ys7
//  Q01859697
//  GDZZON
//  CS-T30-10A

// 猫眼
//    www.ys7.com
//    D02233882
//   QJTZGS
//   CS-DP1-4A1WPFBSR-B

//probeDeviceInfo
//    {"result":{"msg":"设备不在线，未被用户添加","code":"20023","data":{"displayName":"丙烷探测器","subSerial":"D82062349","fullSerial":"JY-BW01I0020191012CCCH999888666","model":"JY-BW01","category":"UNKNOWN","defaultPicPath":"https://statics.ys7.com/device/image/JY-BW01I/101.jpeg","status":0,"supportWifi":2,"releaseVersion":"VERSION_17","version":"V1.0.0 build 191028","availableChannelCount":0,"relatedDeviceCount":0,"supportCloud":"0","supportExt":"{\"support_ap_allseries\":\"1\",\"support_smart_wifi\":\"0\",\"support_local_storage\":\"1\",\"ptz_left_right\":\"0\",\"support_alarm_voice\":\"0\",\"support_ezviz_studio\":\"0\",\"support_upgrade\":\"1\",\"support_device_offline_notify\":\"0\",\"support_auto_offline\":\"1\",\"support_devicelog\":\"1\",\"support_ap_mode\":\"2\",\"support_wifi_userId\":\"1\",\"support_wifi\":\"2\",\"support_hiddns_config\":\"1\",\"support_isapi\":\"1\",\"support_wifi_2.4G\":\"1\",\"ptz_top_bottom\":\"0\",\"support_channel_number\":1}","parentCategory":"COMMON"}}}
